package cn.shuo.app.core.config;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
@Order(1)
public class AspectApiLog {

    private Gson gson = new Gson();

    @Pointcut("execution(public * cn.shuo.app.controller..*(..))")
    public void apiPoint(){}

    @Pointcut("execution(public * cn.niter.forum.controller..*(..))")
    public void webPoint(){}

    /**
     * 如果我们需要一个切点来处理他们两者,我们可以这么配置:
     */
    @Pointcut(value = "webPoint()||apiPoint()")
    public void all(){}

    //请求method前打印内容
    @Before(value = "all()")
    public void methodBefore(JoinPoint joinPoint){
//        log.info("methodBefore");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //打印请求内容
        log.info("===============请求内容===============");
        log.info("请求地址:"+request.getRequestURL().toString());
        log.info("请求方式:"+request.getMethod());
        log.info("请求类方法:"+joinPoint.getSignature());
        log.info("请求类方法参数:"+ Arrays.toString(joinPoint.getArgs()));
        log.info("===============请求内容===============");
    }


    //在方法执行完结后打印返回内容
    @AfterReturning(returning = "o",pointcut = "all()")
    public void methodAfterReturing(Object o ){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        log.info("---------------返回内容----------------");
        log.info("请求地址:"+request.getRequestURL().toString());
        log.info("Response内容:"+gson.toJson(o));
        log.info("---------------返回内容----------------");
    }
}
